package com.taptech.doufu.ui.activity.weex;

import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.taobao.weex.IWXRenderListener;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.common.WXRenderStrategy;
import com.taobao.weex.utils.WXResourceUtils;
import com.taptech.doufu.app.MyActivityManager;
import com.taptech.doufu.listener.IUserLog;
import com.taptech.doufu.manager.UserLogManager;
import com.taptech.doufu.umeng.push.PushManager;
import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.weex.TFWXUtil;
import com.taptech.doufu.weex.statusbar.StatusBarCompatFlavorRom;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.app.WeMediaApplication;
import com.taptech.doufu.constant.GlobalConfig;
import com.taptech.doufu.util.ScreenUtil;
import com.taptech.doufu.weex.QLXGlobal;
import com.taptech.doufu.weex.notification.QLXNotificationCenter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by qlx on 2016/12/7.
 */

public class TFWXActivity extends DiaobaoBaseActivity implements IWXRenderListener,IUserLog {

    WXSDKInstance mWXSDKInstance;
    ArrayList<WXSDKInstance> presentWXSDKInstances;
    protected HashMap param;
    protected LinearLayout lay;
    protected boolean isTranslucent = false;

    private String pageUrl;

    private boolean isServiceUrl = false;

    public String getPageUrl() {
        return pageUrl;
    }

    private String getPageName(String pageUrl) {
        try {
            String[] splitPath = pageUrl.split("\\?")[0].split("/");
            if (splitPath.length > 0) {
                return splitPath[splitPath.length - 1];
            }else{
                return pageUrl;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (this.param == null) {
            this.param = (HashMap) QLXGlobal.getActivityParam(this);
        }
        //用于统计  保存本页面的URL
        pageUrl = getSimpleUrl();
        super.onCreate(savedInstanceState);
        PushManager.getInstance().inAppMessage(this,getPageName(pageUrl));

        //添加用户日志
        addUserLog();
        View rootView = new View(this);
//        if (!isTranslucent) {
//            rootView.setBackgroundColor(WXResourceUtils.getColor("bg|bg"));
//        }
        setContentView(rootView);

        loadPage(getUrl());
    }


    private void loadPage(String url) {

        mWXSDKInstance = new WXSDKInstance(this);
        mWXSDKInstance.registerRenderListener(this);
        /**
         * WXSample 可以替换成自定义的字符串，针对埋点有效。
         * template 是.we transform 后的 js文件。
         * option 可以为空，或者通过option传入 js需要的参数。例如bundle js的地址等。
         * jsonInitData 可以为空。
         * width 为-1 默认全屏，可以自己定制。
         * height =-1 默认全屏，可以自己定制。
         */
        try {
            if (this.param == null) {
                this.param = (HashMap) QLXGlobal.getActivityParam(this);
            }
            HashMap options = this.getOptions();
            //google渠道 、需要支付
            if (GlobalConfig.isGooglePlay && !TextUtils.isEmpty(getSimpleUrl()) && getSimpleUrl().contains("needPay")) {
                initGooglePay();
            }
            if (url.startsWith("http")){
                mWXSDKInstance.renderByUrl("TF", url, options, null,  WXRenderStrategy.APPEND_ASYNC);
            }else {
                mWXSDKInstance.render("TF",url, options , null, WXRenderStrategy.APPEND_ASYNC);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void tf_statusBarInit() {
        //透明状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ) {
            // Translucent status bar
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            try {
                if (WeMediaApplication.getInstance().isDayNightMode_Night){
                    StatusBarCompatFlavorRom.setLightStatusBar(this, false);
                }else {
                    StatusBarCompatFlavorRom.setLightStatusBar(this, true);
                }
            }catch (Exception e){
                e.printStackTrace();
            }

        }
    }


    private String getSimpleUrl() {
        try {
            String url = (String) this.param.get("url");
            return url;
        } catch (Exception e) {
            return "";
        }

    }

    private String getId(String url){
        try {
            String[] param = url.split("\\?");
            String spls = param[1];
            String[] params = spls.split("&");
            for(String value:params){
                if (value.contains("id")){
                    String[] str = value.split("=");
                    return str[1];
                }
            }
            return "";
        } catch (Exception e) {
            return "";
        }
    }


    /**
     * 获取传值额外参数 {data：map} 和bundleUrl同级
     */
    private HashMap getOptions(){
        Object param = this.param;
        HashMap<String,Object> options = new HashMap<String,Object>();
        String url = (String) ((Map) param).get("url");
        options.put("bundleUrl",url);
        if (param instanceof Map){
            param = ((Map) param).get("data");
            if (param instanceof Object){

               if (param instanceof HashMap){
                   options.put("data",param);
               }else {
                   options.put("data",JSON.parseObject(param.toString()));
               }
            }

        }
        return options;
    }
    /**
     * 获取Url
     */
    private String getUrl(){
        Object param = this.param;
        if (param instanceof Map){
            String url = (String) ((Map) param).get("url");
            return TFWXUtil.handleWXUrl(url);
        }
        return "";
    }

    private String getFullUrl(){
        Object param = this.param;
        if (param instanceof Map){
            String url = (String) ((Map) param).get("url");
            return TFWXUtil.handleWXUrlBase(url);
        }
        return "";
    }



    // 移除
    public void removeWeexView(WXSDKInstance instance){
        if (presentWXSDKInstances != null){
            if (presentWXSDKInstances.contains(instance)){


                ViewGroup contentView = (ViewGroup) this.mWXSDKInstance.getContainerView();
                if (contentView instanceof  ViewGroup){

                    contentView.removeView(instance.getContainerView());


                }

                instance.onActivityDestroy();

                presentWXSDKInstances.remove(instance);
            }
        }
    }

    // 在该页面弹出新的Weex页面
    public void presentWeexView(String url , Map data){

        try {

            HashMap option = new HashMap();
            option.put("bundleUrl",url);
            if(data instanceof Map){
                option.put("data",data);
            }
            String  newUrl = TFWXUtil.handleWXUrl(url);

            final WeakReference<TFWXActivity> weakSelf = new WeakReference<TFWXActivity>(this);
            WXSDKInstance wXSDKInstance = new WXSDKInstance(this);
            wXSDKInstance.registerRenderListener(new IWXRenderListener() {
                @Override
                public void onViewCreated(WXSDKInstance instance, View view) {

//                    if (!isTranslucent) {
//                        instance.getContainerView().setBackgroundColor(WXResourceUtils.getColor("bg|bg"));
//                    }

                    TFWXActivity self = weakSelf.get();
                    if (self != null){

                        ViewGroup.LayoutParams params = view.getLayoutParams();
                        params.height = ScreenUtil.getContentHeight(getWindow());

                          view.setBackgroundColor(Color.argb(0,0,0,0));

                          ViewGroup rootView = (ViewGroup) self.mWXSDKInstance.getContainerView();
                        if (rootView instanceof  ViewGroup){
                            rootView.addView(view,params);
                        }
                    }


                }

                @Override
                public void onRenderSuccess(WXSDKInstance instance, int width, int height) {
                       instance.getRootView().bringToFront();
                }

                @Override
                public void onRefreshSuccess(WXSDKInstance instance, int width, int height) {

                }

                @Override
                public void onException(WXSDKInstance instance, String errCode, String msg) {

                }
            });
            if (newUrl.startsWith("http") == true){
                wXSDKInstance.renderByUrl("TF",newUrl, option , null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
            }else {
                wXSDKInstance.render("TF",newUrl, option , null, -1, -1, WXRenderStrategy.APPEND_ASYNC);
            }

            if (presentWXSDKInstances == null){
                presentWXSDKInstances = new ArrayList<WXSDKInstance>();
            }
            presentWXSDKInstances.add(wXSDKInstance);


        }catch (Exception e){

        }

    }

    @Override
    public void onViewCreated(WXSDKInstance instance, View view) {
//        if (!isTranslucent) {
//            instance.getContainerView().setBackgroundColor(WXResourceUtils.getColor("bg|bg"));
//        }
        ViewGroup.LayoutParams params = view.getLayoutParams();
        params.height = ScreenUtil.getContentHeight(getWindow());
        if (lay != null) {
            lay.addView(view,params);
        }else{
            setContentView(view,params);
        }
        final WeakReference<TFWXActivity> weakSelf = new WeakReference<TFWXActivity>(this);
        if (view instanceof ViewGroup){
            ((ViewGroup)view).setOnHierarchyChangeListener(new ViewGroup.OnHierarchyChangeListener() {
                @Override
                public void onChildViewAdded(View parent, View child) {
                    TFWXActivity self = weakSelf.get();
                    if (self != null){
                        if (self.presentWXSDKInstances != null){
                            if (self.presentWXSDKInstances.size() > 0){
                                WXSDKInstance inatance = self.presentWXSDKInstances.get(self.presentWXSDKInstances.size() - 1);
                                if (inatance.getContainerView() != null){
                                    inatance.getContainerView().bringToFront();
                                }

                            }
                        }
                    }
                }

                @Override
                public void onChildViewRemoved(View parent, View child) {

                }
            });

        }

    }

    @Override
    public void onRenderSuccess(WXSDKInstance instance, int width, int height) {
        TTLog.i("Weex初始化","onRenderSuccess");

        Log.e(TFWXActivity.class.getName(),"onRenderSuccess");
    }

    @Override
    public void onRefreshSuccess(WXSDKInstance instance, int width, int height) {
        Log.e(TFWXActivity.class.getName(),"onRefreshSuccess");

    }

    @Override
    public void onException(WXSDKInstance instance, String errCode, String msg) {
        if (isServiceUrl){
            Toast.makeText(this,"抱歉，当前界面加载遇到问题。请截图此信息反馈至【个人中心】-【意见反馈】，或反馈至官方QQ群：460742028。 \n code="+errCode+"  \n  page="+pageUrl+"   \n msg = "+msg,Toast.LENGTH_LONG).show();
        }else{
            //如果本地资源加载失败则加载网络上的资源
            isServiceUrl = true;
            loadPage(getFullUrl());
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(mWXSDKInstance!=null){
            mWXSDKInstance.onActivityResume();
            QLXNotificationCenter.getInstance().postNotify("viewdidappear",null);
            if (presentWXSDKInstances != null){
                for (WXSDKInstance instance:presentWXSDKInstances){
                    instance.onActivityResume();
                }
            }
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        QLXNotificationCenter.getInstance().postNotify("pm_viewdiddisppear",null);
        if(mWXSDKInstance!=null){
            mWXSDKInstance.onActivityPause();
            if (presentWXSDKInstances != null){
                for (WXSDKInstance instance:presentWXSDKInstances){
                    instance.onActivityPause();
                }
            }
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if(mWXSDKInstance!=null){
            mWXSDKInstance.onActivityStop();
            if (presentWXSDKInstances != null){
                for (WXSDKInstance instance:presentWXSDKInstances){
                    instance.onActivityStop();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mWXSDKInstance!=null){
            mWXSDKInstance.onActivityDestroy();
            if (presentWXSDKInstances != null){
                for (WXSDKInstance instance:presentWXSDKInstances){
                    instance.onActivityDestroy();
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            String url = getSimpleUrl();
            if (!TextUtils.isEmpty(url) && url.contains("TFNovel/outlineView.js")) {
                QLXNotificationCenter.getInstance().postNotify("TFOutLineViewKeyCodeBack",null);
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void addUserLog() {
        if (pageUrl == null) {
            return;
        }
        if (pageUrl.contains("TFNovelDetail.js")){ //统计小说详情页面
            //首页点击进入的除外
            if (!"MainHomeActivity".equals(MyActivityManager.getInstance().getParentPageName())&&
                    !"MoreNovel2Activity".equals(MyActivityManager.getInstance().getParentPageName())) {
                UserLogManager.addLog(UserLogManager.LOG_EVENT_NAME_NOVEL_DETAIL,getId(pageUrl));
            }
        }else if (pageUrl.contains("TFPublishWorks.js")||//发布页面
                pageUrl.contains("TFNoticeSystem.js")||  //消息通知页面
                pageUrl.contains("TFMyCoin.js")||        //豆币页面
                pageUrl.contains("TFMyCoinForGoogle.js")||        //豆币页面 for google
                pageUrl.contains("TFBuyMember.js")){    //
            String eventName = "";
            if (pageUrl.contains("TFPublishWorks.js")){
                eventName = "goPublicVC";
            } else if (pageUrl.contains("TFNoticeSystem.js")) {
                eventName = "goNotifyPage";
            } else if (pageUrl.contains("TFMyCoin.js")) {
                eventName = "goRecharge";
            } else if (pageUrl.contains("TFMyCoinForGoogle.js")) {
                eventName = "goRechargeForGoogle";
            } else if (pageUrl.contains("TFBuyMember.js")) {
                eventName = "goVipPayView";
            }
            UserLogManager.addLog(eventName,getId(pageUrl));
        }
    }
}
